#ifndef GROUPFILEREADER_H_INCLUDED
#define GROUPFILEREADER_H_INCLUDED
#include "subjectfilereader.h"
#include "../Entities/studentgroup.h"

namespace GroupFileReader{
    typedef std::vector<StudentGroup> StudentGroupList;

    StudentGroupList read(const char *filename, SubjectFileReader::SubjectList &list){
        StudentGroupList ret;

        int s = list.size();

        std::ifstream file(filename);
        if(!file.is_open())
            throw "file cannot be loaded";
        int id = 1;
        while(!file.eof()){
            char line[500];
            file.getline(line, 500);

            StringTokenizer tokenizer(line, "%");

            if(!tokenizer.hasMoreTokens())
                throw "invalid file format.";
            std::string name = tokenizer.nexToken();

            if(!tokenizer.hasMoreTokens())
                throw "invalid file format.";
            try{
                int size = atoi(tokenizer.nexToken().c_str());
                StudentGroup a(name.c_str(), size, id++);
                while(tokenizer.hasMoreTokens()){
                    try{
                        int index = atoi(tokenizer.nexToken().c_str());
                        if(index > s || index < 1)
                            throw "subject id is invalid.";
                        a.addSubject(list[index-1]);
                    } catch(...){
                        throw "invalid file format.";
                    }
                }
                ret.push_back(a);
            } catch(...){
                throw "invalid file format.";
            }

        }

        return ret;
    }
}


#endif // GROUPFILEREADER_H_INCLUDED
